Using attr() with Pseudo-Elements in CSS
The CSS attr() function allows pseudo-elements like ::before and ::after to display the value of an HTML attribute dynamically. This enables you to generate content based on the element's attributes without modifying the HTML.
Use content: attr(attribute-name); to insert the value of a specific attribute.
Only string-based attributes can be displayed using attr(). Numeric or URL values can also be used with certain properties like content.
The attr() function can be combined with other text or symbols in the content property, e.g., content: 'Note: ' attr(data-note);.
This method is ideal for tooltips, labels, counters, or displaying metadata dynamically.
In this example, the ::after pseudo-element reads the data-source attribute of the paragraph and displays it in parentheses after the text. You can change the attribute in HTML, and the pseudo-element will automatically reflect the new value.
Use attr() for dynamically generated text content without extra markup.
Combine with CSS styling like color, font-weight, or text-transform for visual emphasis.
Avoid using pseudo-elements with attr() for interactive or functional content that requires JavaScript events.
Test across browsers; basic attr() support for content is widely supported, but other properties may have limited compatibility.